import traceback

from flask import Flask, jsonify, request
from flask_cors import CORS
import process
import os

app = Flask(__name__)
cors = CORS(app, support_credentials=True)


@app.route('/saveAll', methods=['POST'])
def saveAll():
    print(request)
    success = False
    message = "Failed saving"
    if request.method == 'POST':
        try:
            print(request.form)
            text_content = request.form['content']
            auto_labeled = request.form['autoLabeled']
            labels = request.form['labels']
            process.saveAll(text_content, auto_labeled, labels)
            success = True
            message = "Successfully saved"
        except:
            traceback.print_exc()
            success = False
            message = "Failed saving"
    response = {
        "success": success,
        "content": message,
        "message": message
    }
    return jsonify(response)


@app.route('/analyze', methods=['POST'])
def analyze():
    print(request)
    result = {
        "autoLabeled": [],
        "labels": {
            "noun": [],
            "verb": [],
            "adj": []
        }
    }
    success = False
    message = "Failed analyzing"
    if request.method == 'POST':
        try:
            data = request.form['content']
            result['autoLabeled'], result['labels'] = process.extractFromContent(data)
            success = True
            message = "Successfully analyzed"
        except:
            traceback.print_exc()
            success = False
            message = "Failed analyzing"
    response = {
        "success": success,
        "content": result,
        "message": message
    }
    return jsonify(response)


@app.route('/uploadFile', methods=['POST'])
def uploadFile():
    print(request)
    content = ''
    success = False
    message = "Failed uploading"
    if request.method == 'POST':
        try:
            f = request.files['file']
            print(request.files)
            f.save(f.filename)
            content = process.getContent(f.filename)
            os.remove(f.filename)
            success = True
            message = "File successfully uploaded"
        except:
            traceback.print_exc()
            success = False
            message = "Failed uploading"
    response = {
        "success": success,
        "content": content,
        "message": message
    }
    return jsonify(response)


if __name__ == '__main__':
    app.run(port=5000)
